<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片页 -->
        <el-card class="box-card">
            <!-- 搜索栏 -->
            <div>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserInfo()">
                            <el-button slot="append" icon="el-icon-search" @click="getUserInfo"></el-button>
                        </el-input>
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                    </el-col>
                </el-row>
            </div>
            <!-- 用户信息列表 -->
            <el-table :data="queryData.users" stripe border>
                <el-table-column label="#" type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch
                        v-model="scope.row.mg_state"
                        active-color="#13ce66"
                        inactive-color="#ff4949" @change=changeState(scope.row)>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="400px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="editUser(scope.row.id)">修改</el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="handleDeleteUser(scope.row.id)">删除</el-button>
                        <el-button type="primary" icon="el-icon-s-tools" @click="showRole(scope.row)">分配角色</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 7]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryData.total">
            </el-pagination>
            <!-- 添加用户对话框 -->
            <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%" @close='clearAddUserInfo'>
            <el-form :model="addUserInfo" :rules="addUserRules" ref="addUserForm" label-width="100px">

                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserInfo.username"></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserInfo.password" type="password"></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserInfo.email"></el-input>
                </el-form-item>   

                <el-form-item label="手机号码" prop="mobile">
                    <el-input v-model="addUserInfo.mobile"></el-input>
                </el-form-item>     

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAdd">确 定</el-button>
            </span>
            </el-dialog>
            <!-- 添加修改用户信息对话框 -->
            <el-dialog
            title="修改用户信息"
            :visible.sync="editDialogVisible"
            width="60%">
            <el-form :model="editUserInfo" :rules="addUserRules" ref="editUserForm" label-width="100px">

                <el-form-item label="用户名">
                    <el-input v-model="editUserInfo.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="editUserInfo.email"></el-input>
                </el-form-item>
                <el-form-item label="电话号码" prop="mobile">
                    <el-input v-model="editUserInfo.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 给用户分配角色的对话框 -->
            <el-dialog title="分配角色" :visible.sync="roleDialogVisible" @close="clearEditRoleForm">
                <div class="selectRole">
                    <p>当前用户：{{roleInfo.username}}</p>
                    <p>当前角色：{{roleInfo.role_name}}</p>
                    <p>分配新角色：
                        <el-select placeholder="请选择用户角色" v-model="selectedRid" @focus="getAllRoles()">
                            <el-option v-for="item in allRoles" :label="item.roleName" :value="item.id" :key= "item.id"></el-option> 
                        </el-select>
                    </p>
                </div>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="roleDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitRoleForm">确 定</el-button>
                </div>
                
            </el-dialog>
        </el-card>
    </div>
</template>
<style lang="less" scoped>
    .el-table{
        margin-top: 30px;
    }
    .el-breadcrumb{
        margin-bottom:20px;
    }
    .el-pagination{
        margin-top: 20px;
    }
    .el-input__inner{
        width: 100%;
    }
    .selectRole{
        margin-left: 20px;
        p{
            margin-top: 30px;
        }
    }
</style>
<script>
export default{
    data(){
        var checkEmail = (rule,value,callback)=>{
            if (value) {
                var regEmail=/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
                if (regEmail.test(value)) {
                    return callback()
                }
            callback(new Error('邮箱格式错误！'));
            } else return callback()
        }
        
        var checkmobile = (rule,value,callback)=>{
            if (value) {
                var regmobile=/^1[0-9]{10}$/;
                if (regmobile.test(value)) {
                    return callback()
                }
                callback(new Error('手机号码格式错误！'));                
            }else return callback()
        }
        return{
            search:'',
            queryInfo:{
                query:'',
                pagenum:1,
                pagesize:7
            },
            queryData:[],
            editUserInfo:{
                id:'',
                rid:'',
                username:'',
                mobile:'',
                email:'',
            },
            total:0,
            addDialogVisible:false,
            editDialogVisible:false,
            deleteDialogVisible:false,
            roleDialogVisible:false,
            addUserInfo:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            addUserRules:{
                username:[{ required: true, message: '请输入姓名', trigger: 'blur' },{ max:10,min:3, message: '请输入姓名', trigger: 'blur' }],

                password:[{ required: true, message: '请输入密码', trigger: 'blur' },],

                email:[{ validator: checkEmail, trigger: 'blur' }],

                mobile:[{ validator: checkmobile, trigger: 'blur' }]
            },
            allRoles:[],
            roleInfo:'',
            selectedRid:''
        }
    },
    created(){
        this.getUserInfo()
    },
    methods:{
        async getUserInfo(){
            var { data:response }=await this.$http.get('/users',{ params:this.queryInfo})
            // console.log(response);
            if (response.meta.status!=200) {
                // console.log(response.meta.msg);
                this.$message.error('获取用户列表失败！')
            } else {
                this.queryData = response.data;
            }
        },
        handleSizeChange(pageSize){
            this.queryInfo.pagesize = pageSize;
            this.getUserInfo();
        },
        handleCurrentChange(currentPage){
            // console.log(currentPage);
            this.queryInfo.pagenum=currentPage;
            this.getUserInfo()
        },
        async changeState(document){
            // console.log(document.mg_state);
            var {data:response}= await this.$http.put(`users/${document.id}/state/${document.mg_state}`)
            if (response.meta.status != 200) {
                this.$message.error(response.meta.msg)
                document.mg_state =! document.mg_state;
            }else{
                this.$message.success(response.meta.msg);
            }
        },
        async handleAdd(){
            this.$refs.addUserForm.validate(async (valid)=>{
                if (!valid) {
                    return false;
                } 
                var {data:response}= await this.$http.post('/users',this.addUserInfo);
                if (response.meta.status!=201) {
                    this.$message.error(response.meta.msg);
                } else {
                    this.$message.success('添加用户成功');
                    this.addDialogVisible = false;
                    this.getUserInfo();
                }
            });

            },
        clearAddUserInfo(){
            this.$refs.addUserForm.resetFields();
        },
        async editUser(id){
            // this.$refs.editUserForm.resetFields();
            var {data:response} = await this.$http.get(`users/${id}`);
            if (response.meta.status!=200) {
                this.$message.error(response.meta.msg);
            } else this.editUserInfo = response.data;
            this.editDialogVisible = true;
        },
        async submitEdit(){
            
            this.$refs.editUserForm.validate(async (valid)=>{
                if (valid) {
                    this.editDialogVisible = false;
                    var {data:response} = await this.$http.put(`/users/${this.editUserInfo.id + 0}`,this.editUserInfo);
                    if (response.meta.status==200) {
                        this.getUserInfo();
                        this.$message.success(response.meta.msg);
                    } else {
                        this.$message.error(response.meta.msg)
                    }
                }
            })
        },
        async handleDeleteUser(id){        
            const confirmResponse = await this.$confirm(`此操作将永久删除该用户, 是否继续?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).catch((error)=>(error));
            if (confirmResponse == 'confirm') {
                const {data:response} = await this.$http.delete('users/'+id);
                if (response.meta.status == 200) {
                    this.$message.success(response.meta.msg)
                } else {
                    this.$message.error(response.meta.msg)
                }
            }
            this.getUserInfo();
        },
         showRole(roleInfo){
            // 展示用户名，当前角色。
            this.roleInfo = roleInfo;
            console.log(roleInfo);
            this.roleDialogVisible = true;
        },
        clearEditRoleForm(){
           this.selectedRid='';
        },
        //获取角色数据，包括各个角色拥有的权限
        async getAllRoles(){
            const {data:response} = await this.$http.get('/roles');
            if (response.meta.status==200) {
                this.allRoles = response.data;
            } else {
                this.$message.error(response.meta.msg);
            }
        },
        async submitRoleForm(){
            this.roleDialogVisible = false;
            var {data:response} = await this.$http.put(`users/${this.roleInfo.id}/role`,{'rid':this.selectedRid});
            if (response.meta.status == 200) {
                this.$message.success(response.meta.msg);
                this.getUserInfo();
            } else {
                this.$message.error(response.meta.msg);
            }
        }
        
    },
        
}
</script>